package com.jielin.handling.controller.dzzj;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.amazonaws.services.s3.model.ObjectMetadata;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jielin.handling.Annotation.MyPower;
import com.jielin.handling.bean.AppResult;
import com.jielin.handling.entity.auditresult.AuditResult;
import com.jielin.handling.entity.dzzj.JZBody;
import com.jielin.handling.entity.dzzj.JZHeader;
import com.jielin.handling.entity.dzzj.OrgAndJYIp;
import com.jielin.handling.entity.dzzj.Video;
import com.jielin.handling.entity.police.PoliceMan;
import com.jielin.handling.entity.tsuspect.TSuspec;
import com.jielin.handling.entity.unit.Organization;
import com.jielin.handling.entity.video.PubliceVideo;
import com.jielin.handling.entity.vo.PoliceVo;
import com.jielin.handling.page.DataGrid;
import com.jielin.handling.service.dzzj.VideoService;
import com.jielin.handling.service.police.PoliceCaseService;
import com.jielin.handling.service.police.PoliceManService;
import com.jielin.handling.service.unit.UnitService;
import com.jielin.handling.service.xsky.XskyService;
import com.jielin.handling.util.ConstantUtil;
import com.jielin.handling.util.DateUtil;
import com.jielin.handling.util.StringUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author WIN10 警翼记录仪音视频
 */
@CrossOrigin
@RestController
@RequestMapping("/dzzj")
@MyPower(name = "警翼记录仪音视频", type = 0, url = "/dzzj")
@Slf4j
public class VideoController {
    @Autowired
    private VideoService videoService;
    @Autowired
    private XskyService xskyService;
    @Autowired
    private PoliceManService policeManService;
    @Autowired
    private PoliceCaseService policeCaseService;
    @Autowired
    private UnitService unitService;

    /**
     * 根据单位编号查询此单位辖区所有音视频关联率
     *
     * @param unitCode 单位编号
     * @return
     */
    @MyPower(name = "根据单位编号查询此单位辖区所有音视频关联率", url = "/correlationRate")
    @RequestMapping("/correlationRate")
    public AppResult correlationRate(String unitCode) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        log.info("..........correlationRate");
        List<Map> correlations = videoService.findCaseAVCorrelationRate(unitCode);

        data.put("value", correlations);
        result.setCode(200);
        result.setMsg("查询成功!");
        result.setData(data);
        return result;
    }

    /**
     * 根据单位编号查询此单位辖区所有案件的音视频关联率
     *
     * @param unitCode 单位编号
     * @return
     */
    @MyPower(name = "根据单位编号查询此单位辖区所有案件的音视频关联率", url = "/findRateByUnitCode")
    @RequestMapping("/findRateByUnitCode")
    public AppResult findRateByUnitCode(String unitCode) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        log.info("..........findRateByUnitCode");
        List<Map> correlations = videoService.findRateByUnitCode(unitCode);

        data.put("value", correlations);
        result.setCode(200);
        result.setMsg("查询成功!");
        result.setData(data);
        return result;
    }

    /**
     * 根据民警编号查询此民警处理的案件音视频关联率
     *
     * @param policeCode 警员编号
     * @param policeId   警员ID
     * @return
     */
    @MyPower(name = "根据民警编号查询此民警处理的案件音视频关联率", url = "/findRateByPoliceCode")
    @RequestMapping("/findRateByPoliceCode")
    public AppResult findRateByPoliceCode(String policeCode, String policeId) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        log.info("..........findRateByPoliceCode");
        List<Map> correlations = videoService.findRateByPoliceCode(policeCode, policeId);

        data.put("value", correlations);
        result.setCode(200);
        result.setMsg("查询成功!");
        result.setData(data);
        return result;
    }

    /**
     * 根据民警编号查询此民警记录仪的文件列表
     *
     * @param policeCode 警员编号
     * @param fileType   媒体类型(1:图片 2:视频 3:音频)
     * @param startTime  开始时间
     * @param endTime    结束时间
     * @param
     * @return
     */
    @MyPower(name = "根据民警编号查询此民警记录仪的文件列表", url = "/findRecorderFileList")
    @RequestMapping("/findRecorderFileList")
    public AppResult findRecorderFileList(String policeCode,
                                          @RequestParam(name = "fileType", required = false) String fileType,
                                          @RequestParam(name = "startTime", required = false) String startTime,
                                          @RequestParam(name = "endTime", required = false) String endTime) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        // 查询未关联
//		List<Video> files = videoService.findRecorderFileList(policeCode, fileType, startTime, endTime, "0", "", "");
        // 查询所有
        List<Video> files = videoService.findRecorderFileList(policeCode, fileType, startTime, endTime, "", "", "");
        data.put("value", files);
        result.setCode(200);
        result.setMsg("查询成功!");
        result.setData(data);
        return result;
    }

    /**
     * 根据民警编号查询此民警记录仪文件列表
     *
     * @param pageNum
     * @param pageSize
     * @param policeCode        警员编号
     * @param fileType          媒体类型(1:图片 2:视频 3:音频)
     * @param startTime         开始时间
     * @param endTime           结束时间
     * @param correlationStatus 是否已关联 0未 1已
     * @param caseCode          案件编号
     * @param caseName          案件名称
     * @return
     */
    @MyPower(name = "根据民警编号查询此民警记录仪文件列表", url = "/findRecorderFileListEX", isPublic = true)
    @RequestMapping("/findRecorderFileListEX")
    public AppResult findRecorderFileListEX(@RequestParam(name = "pageNum", defaultValue = "1") int pageNum,
                                            @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
                                            String policeCode, String fileType, String startTime, String endTime, String correlationStatus, String caseCode, String caseName) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        Page<Video> startPage = PageHelper.startPage(pageNum, pageSize);// 使用分页插件方法
        videoService.findRecorderFileList(policeCode, fileType, startTime, endTime, correlationStatus, caseCode, caseName);
        DataGrid dg = new DataGrid();
        dg.setRows(startPage.getResult());
        dg.setTotal(startPage.getTotal());
        data.put("value", dg);
        result.setCode(200);
        result.setMsg("查询成功!");
        result.setData(data);
        return result;
    }

    /**
     * 将记录仪文件与案件相关联
     *
     * @param recorderFileId 记录仪文件ID
     * @param docId          文件夹ID
     * @param fileName       文件名称
     * @param fileUrl        文件地址
     * @param fileType       文件类型
     * @param thumburl       缩略图地址
     * @param caseCode       案件编号
     * @return
     */
    @MyPower(name = "将记录仪文件与案件相关联", url = "/correlation")
    @RequestMapping("/correlation")
    public AppResult correlation(HttpServletRequest request, String recorderFileId, String docId, String fileName,
                                 String fileUrl, String fileType, String thumburl, String caseCode) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        log.info("..........saveRecorderFileCorrelation");
        int i = videoService.saveRecorderFileCorrelation(recorderFileId, docId, fileName, fileUrl, fileType, thumburl);
        if (i == -1) {
            data.put("value", i);
            result.setCode(-1);
            result.setMsg("将记录仪文件与案件相关联失败！");
            result.setData(data);
        } else if (i == -2) {
            data.put("value", i);
            result.setCode(-1);
            result.setMsg("将记录仪文件与案件相关联失败！(可能原因：1.查询不到文件夹信息2.传入的记录仪文件信息不正确)");
            result.setData(data);
        } else {
            data.put("value", i);
            result.setCode(200);
            result.setMsg("将记录仪文件与案件相关联成功！");
            result.setData(data);
//			getRecorderFile(request, recorderFileId, fileType, caseCode); // TODO 警综执法记录仪视频采集接口
            log.info("执法记录仪视频采集接口");
        }
        return result;
    }

    /**
     * 根据记录仪id查询记录仪文件信息
     *
     * @param fileId 记录仪文件id
     * @return
     */
    @MyPower(name = "根据记录仪id查询记录仪文件信息", url = "/findRecorderFileById")
    @RequestMapping("/findRecorderFileById")
    public AppResult findRecorderFileById(String fileId) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        log.info("..........findRecorderFileById");
        Video files = videoService.findRecorderFileById(fileId);

        data.put("value", files);
        result.setCode(200);
        result.setMsg("查询成功!");
        result.setData(data);
        return result;
    }

    /**
     * 执法记录仪视频采集接口
     *
     * @return
     */
    @RequestMapping("/getRecorderFile")
    public void getRecorderFile(HttpServletRequest request, String recorderFileId, String fileType, String caseCode) {
        log.info("执法记录仪视频采集接口recorderFileId{},fileType{},caseCode{}", recorderFileId, fileType, caseCode);
        if (StringUtil.isEmpty(recorderFileId) || StringUtil.isEmpty(fileType) || StringUtil.isEmpty(caseCode)) {
            log.info("传的参数不完整记录仪文件recorderFileId：" + recorderFileId);
            log.info("传的参数不完整文件类型fileType：" + fileType);
            log.info("传的参数不完整案件编号caseCode：" + caseCode);
            return;
        } else {

            Video v = videoService.findRecorderFileById(recorderFileId);
            PoliceMan pm = policeManService.findPoliceManByCode(v.getPoliceNo());
            Organization o = null;
            // MaterialFile mf = materialFileService.findFileById(v.getCorrelationFileId());

            if (v == null) {
                log.info("没有查询到记录仪文件信息");
                v = new Video();
            }
            if (pm == null) {
                log.info("没有查询到警员信息");
                pm = new PoliceMan();
            } else {
                o = unitService.findUnitInfoById(pm.getOrganizationid());
            }
            // if (mf == null) {
            // log.info("没有查询到关联的文件信息");
            // mf = new MaterialFile();
            // }
            if (o == null) {
                log.info("没有查询到改警员的单位信息");
                o = new Organization();
            }

            JZHeader jzHeader = new JZHeader();
            jzHeader.setIDCardNo(StringUtil.isEmpty(pm.getIdCardNo()) ? v.getPoliceNo() : pm.getIdCardNo());// 如果查询不到身份证号码就传警员编号
            jzHeader.setServiceId("8CA82EEFDABD78E3EF50DE06133BD53F");
            // 测试库 jzHeader.setInstanceId("6A48F8E7C69D1E745F825CDF0C4594A6");
            jzHeader.setInstanceId("BCD44AD1390172DD6360F641335727CC");// 恩施正式库
            jzHeader.setIdUnique(request.getRemoteAddr());
            jzHeader.setOrgName(v.getOrgName());
            jzHeader.setOrgCode(v.getOrgNo());
            jzHeader.setUserName(
                    StringUtil.isEmpty(pm.getName()) ? v.getFileName().substring(0, v.getFileName().indexOf("@"))
                            : pm.getName());

            /*
             * JZHeader jzHeader = new JZHeader(); jzHeader.setIDCardNo("00000");
             * jzHeader.setServiceId("8CA82EEFDABD78E3EF50DE06133BD53F");
             * jzHeader.setInstanceId("6A48F8E7C69D1E745F825CDF0C4594A6");
             * jzHeader.setIdUnique(getClientIpAddr(request));
             * jzHeader.setOrgName("000000"); jzHeader.setOrgCode("000000");
             * jzHeader.setUserName("000000");
             */

            JZBody jzBody = new JZBody();
            jzBody.setJYBH(v.getPoliceNo());
            jzBody.setWJMC(v.getFileName());
            jzBody.setWJLX("视频");
            jzBody.setSJLY("30");// 固定写30
            jzBody.setWJDX(v.getFileLength());
            // jzBody.setBFDZ(mf.getUrl());// 文件的存放地址
            OrgAndJYIp jy = videoService.findRecorderIPbyOrgNo(v.getOrgNo());// 根据单位编号查询对应的警翼工作站ip
            // jzBody.setBFDZ("http://" + v.getUploadStationIp() + "/?_a=video&id="
            // +v.getDataId());// 警翼工作站的播放地址{v.getUploadStationIp()：警翼记录仪文件上传的ip}
            if (fileType.equals("2")) { // 如果是视频
                jzBody.setBFDZ("http://" + (StringUtil.isEmpty(jy.getJYip()) ? "null" : jy.getJYip()) + ":"
                        + (StringUtil.isEmpty(jy.getJYport()) ? "null" : jy.getJYport()) + "/?_a=video&id="
                        + v.getDataId());// 警翼工作站的播放地址
            } else {
                jzBody.setBFDZ(v.getPlayurl());
            }
            /*
             * jzBody.setJYBH("JLY" +"00000000" + DateUtil.getStringFormatDate() + "000");
             * jzBody.setWJMC("000"); jzBody.setWJLX("视频"); jzBody.setSJLY("30");
             * jzBody.setSJLY("警翼工作站"); jzBody.setWJDX("20"); jzBody.setBFDZ("000");
             * jzBody.setDJSJ(DateUtil.getStringFormatDate());// (李成阳：不用传)
             */

            // 开始拍摄时间
            String KSPSSJ = DateUtil.getFormatDate(v.getCaptureDate(), DateUtil.DATE_FORMAT_NUMBER);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(v.getCaptureDate());
            calendar.add(Calendar.MILLISECOND, v.getFileDuration().intValue());
            // 结束拍摄时间
            String JSPSSJ = DateUtil.getFormatDate(calendar.getTime(), DateUtil.DATE_FORMAT_NUMBER);

            String GLJQBH = policeCaseService.findAlertCodeByCaseCode(caseCode);// 关联警情编号

            jzBody.setGLJQBH(GLJQBH); // 关联警情编号(必填)
            // jzBody.setSFSD(""); // VARCHAR2(1) 编码 是否锁定(李成阳：先不传)
            jzBody.setKSPSSJ(KSPSSJ); // VARCHAR2(26) 日期时间 开始拍摄时间
            jzBody.setJSPSSJ(JSPSSJ); // VARCHAR2(26) 日期时间 结束拍摄时间
            jzBody.setSCRQ(DateUtil.getFormatDate(v.getCreationDate(), DateUtil.DATE_FORMAT_NUMBER));
            // VARCHAR2(26) 日期时间 上传日期
            jzBody.setSJCD(v.getFileDuration() + "");
            // VARCHAR2(20) 时间长度
            jzBody.setDJRZH(StringUtil.isEmpty(pm.getIdCardNo()) ? v.getPoliceNo() : pm.getIdCardNo());
            // VARCHAR2(18) 登记人身份证号
            jzBody.setDJRXM(
                    StringUtil.isEmpty(pm.getName()) ? v.getFileName().substring(0, v.getFileName().indexOf("@"))
                            : pm.getName()); // VARCHAR2(30) 登记人姓名
            jzBody.setDJDW(StringUtil.isEmpty(o.getHandleUnitCode()) ? v.getOrgNo() : o.getHandleUnitCode());
            // VARCHAR2(12) 登记单位
            jzBody.setDJDWMC(StringUtil.isEmpty(o.getOrganizationName()) ? v.getOrgName() : o.getOrganizationName());
            // VARCHAR2(100) 登记单位名称
            jzBody.setXGRZH(StringUtil.isEmpty(pm.getIdCardNo()) ? v.getPoliceNo() : pm.getIdCardNo());
            // VARCHAR2(18) 修改人身份证号
            jzBody.setXGRXM(
                    (StringUtil.isEmpty(pm.getName()) ? v.getFileName().substring(0, v.getFileName().indexOf("@"))
                            : pm.getName())); // VARCHAR2(30) 修改人姓名
            // jzBody.setXGSJ(""); // VARCHAR2(14) 日期时间 修改时间(李成阳：不用传)
            jzBody.setXGDW(StringUtil.isEmpty(o.getHandleUnitCode()) ? v.getOrgNo() : o.getHandleUnitCode());
            // VARCHAR2(12) 修改单位
            jzBody.setXGDWMC(StringUtil.isEmpty(o.getOrganizationName()) ? v.getOrgName() : o.getOrganizationName());
            // VARCHAR2(100) 修改单位名称

            // 相关视频路径上传到警综
            String result123 = "";
            try {
                result123 = getResult(jzHeader, jzBody);
            } catch (IOException e) {
                log.info("相关视频路径上传到警综出错了。。。。");
                e.printStackTrace();
            }

            log.info(result123);

        }

        /*
         * data.put("value", ""); result.setCode(-1); result.setMsg("执法记录仪视频采集失败！");
         * result.setData(data);
         *
         * return result;
         */
    }

    private static String getResult(JZHeader jzHeader, JZBody jzBody) throws IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://10.72.39.102:6060/gateway/rest/invoke");
        HashMap<String, String> map = new HashMap<>();
        map.put("JYBH", jzBody.getJYBH());
        map.put("WJMC", jzBody.getWJMC());
        map.put("WJLX", jzBody.getWJLX());
        map.put("SJLY", jzBody.getSJLY());
        map.put("BFDZ", jzBody.getBFDZ());
        map.put("GLJQBH", jzBody.getGLJQBH());
        map.put("KSPSSJ", jzBody.getKSPSSJ());
        map.put("JSPSSJ", jzBody.getJSPSSJ());
        map.put("SCRQ", jzBody.getSCRQ());
        map.put("SJCD", jzBody.getSJCD());
        map.put("DJRZH", jzBody.getDJRZH());
        map.put("DJRXM", jzBody.getDJRXM());
        map.put("DJDW", jzBody.getDJDW());
        map.put("DJDWMC", jzBody.getDJDWMC());
        map.put("XGRZH", jzBody.getXGRZH());
        map.put("XGRXM", jzBody.getXGRXM());
        map.put("XGDW", jzBody.getXGDW());
        map.put("XGDWMC", jzBody.getXGDWMC());
        log.info(JSONObject.toJSONString(map));
        StringEntity entity = new StringEntity(JSONObject.toJSONString(map), ContentType.APPLICATION_JSON);
        entity.setContentEncoding("UTF-8");
        httpPost.addHeader("IDCardNo", jzHeader.getIDCardNo());
        httpPost.addHeader("serviceId", jzHeader.getServiceId());
        httpPost.addHeader("instanceId", jzHeader.getInstanceId());
        httpPost.addHeader("idUnique", jzHeader.getIdUnique()); // 调用人ip
        httpPost.addHeader("orgName", jzHeader.getOrgName()); // 调用单位名称
        httpPost.addHeader("orgCode", jzHeader.getOrgCode()); // 单位代码
        httpPost.addHeader("userName", jzHeader.getUserName());
        /*
         * httpPost.addHeader("IDCardNo", "420221197206240417");
         * httpPost.addHeader("serviceId", "8CA82EEFDABD78E3EF50DE06133BD53F ");
         * httpPost.addHeader("instanceId", "6A48F8E7C69D1E745F825CDF0C4594A6 ");
         * httpPost.addHeader("idUnique", "127.0.0.1"); 调用人ip
         * httpPost.addHeader("orgName", "fang"); 调用单位名称 httpPost.addHeader("orgCode",
         * "888888888888"); 单位代码 httpPost.addHeader("userName", "使用人");
         */
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.setEntity(entity);
        CloseableHttpResponse execute = client.execute(httpPost);
        String s = EntityUtils.toString(execute.getEntity(), "UTF-8");
        return s;
    }

    /***
     * 获取客户端ip地址(可以穿透代理)
     *
     * @param request
     * @return
     */
    public static String getClientIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_CLUSTER_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_FORWARDED");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_VIA");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("REMOTE_ADDR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 视频管理中心随机取出6张图片
     *
     * @param unitcode
     * @return
     */
    @MyPower(name = "视频管理中心随机取出6张图片", url = "/selectRandomVideo", isPublic = true)
    @RequestMapping("/selectRandomVideo")
    public AppResult selectRandomVideo(String unitcode, String policeCode) {
        log.info("unicode:{}", unitcode);
        AppResult appResult = new AppResult();
        JSONObject data = new JSONObject();
        if (StringUtil.isEmpty(unitcode)) {
            data.put("value", 0);
            appResult.setCode(-1);
            appResult.setMsg("参数为空");
            appResult.setData(data);
            return appResult;
        }
        String[] array = unitcode.split(",");
        Map map = new HashMap();
        map.put("array", array);
        map.put("policeCode", policeCode);
        List<Video> list = videoService.selectRandomVideo(map);
        //用PageInfo对结果进行包装
        data.put("list", list);
        appResult.setCode(200);
        appResult.setMsg("图片获取成功!");
        appResult.setData(data);
        return appResult;
    }

    /**
     * 最新上传----视频管理首页
     *
     * @param unitcode
     * @return
     */
    @MyPower(name = "获取最新上传信息", url = "/selectLatesVideo", isPublic = true)
    @RequestMapping("/selectLatesVideo")
    public AppResult selectLatesVideo(String unitcode, String policeCode) {
        log.info("unicode:{}", unitcode);
        AppResult appResult = new AppResult();
        JSONObject data = new JSONObject();
        if (StringUtil.isEmpty(unitcode)) {
            data.put("value", 0);
            appResult.setCode(-1);
            appResult.setMsg("参数为空");
            appResult.setData(data);
            return appResult;
        }
        String[] array = unitcode.split(",");
        Map map = new HashMap();
        map.put("array", array);
        map.put("policeCode", policeCode);
        List<Video> list = videoService.selectLatesVideo(map);
        //用PageInfo对结果进行包装
        data.put("list", list);
        appResult.setCode(200);
        appResult.setMsg("获取最新上传成功!");
        appResult.setData(data);
        return appResult;
    }

    /**
     * 首页推荐
     *
     * @param unitcode
     * @return
     */
    @MyPower(name = "首页推荐信息", url = "/selectRecommend", isPublic = true)
    @RequestMapping("/selectRecommend")
    public AppResult selectRecommend(String unitcode, String policeCode) {
        log.info("unicode:{}", unitcode);
        AppResult appResult = new AppResult();
        JSONObject data = new JSONObject();
        if (StringUtil.isEmpty(unitcode)) {
            data.put("value", 0);
            appResult.setCode(-1);
            appResult.setMsg("参数为空");
            appResult.setData(data);
            return appResult;
        }
        String[] array = unitcode.split(",");
        Map map = new HashMap();
        map.put("array", array);
        map.put("policeCode", policeCode);
        List<Video> list = videoService.selectRecommend(map);
        //用PageInfo对结果进行包装
        data.put("list", list);
        appResult.setCode(200);
        appResult.setMsg("获取推荐成功");
        appResult.setData(data);
        return appResult;
    }

    /**
     * 随机抽查
     *
     * @param queryCondition
     * @return
     */
    @MyPower(name = "随机抽查", url = "/selectRandomSampling", isPublic = true)
    @RequestMapping("/selectRandomSampling")
    public AppResult selectRandomSampling(@RequestBody JSONObject queryCondition) {
        AppResult appResult = new AppResult();
        JSONObject data = new JSONObject();
        log.info("user query...");
        Video video1 = new Video();
        int pageNum = queryCondition.getIntValue("pageNum");
        int pageSize = queryCondition.getIntValue("pageSize");
        video1.setQueryCondition(queryCondition);
        video1.setPage(pageNum, pageSize);
        if (StringUtil.isEmpty(video1.getUnitCodes())) {
            data.put("value", 0);
            appResult.setCode(-1);
            appResult.setMsg("参数为空");
            appResult.setData(data);
            return appResult;
        }

        String[] unitCodes = video1.getUnitCodes().split(",");
        video1.setArray(unitCodes);
        List<Video> orderList = videoService.selectRandomSampling(video1);
        PageInfo<Video> dataGrid = new PageInfo<>(orderList);
        data.put("datagrid", dataGrid);
        appResult.setCode(200);
        appResult.setMsg("query success");
        appResult.setData(data);
        return appResult;

    }

    /**
     * 办案视频
     *
     * @param queryCondition
     * @return
     */
    @MyPower(name = "获取办案视频信息", url = "/selectCaseVideo", isPublic = true)
    @RequestMapping("/selectCaseVideo")
    public AppResult selectCaseVideo(@RequestBody JSONObject queryCondition) {
        AppResult appResult = new AppResult();
        JSONObject data = new JSONObject();
        log.info("user query...");
        Video video1 = new Video();
        int pageNum = queryCondition.getIntValue("pageNum");
        int pageSize = queryCondition.getIntValue("pageSize");
        video1.setQueryCondition(queryCondition);
        video1.setPage(pageNum, pageSize);
        if (StringUtil.isEmpty(video1.getUnitCodes())) {
            data.put("value", 0);
            appResult.setCode(-1);
            appResult.setMsg("参数为空");
            appResult.setData(data);
            return appResult;
        }
        String[] unitCodes = video1.getUnitCodes().split(",");
        video1.setArray(unitCodes);
        List<Video> orderList = videoService.selectCaseVideo(video1);
        PageInfo<Video> dataGrid = new PageInfo<>(orderList);
        data.put("datagrid", dataGrid);
        appResult.setCode(200);
        appResult.setMsg("query success");
        appResult.setData(data);
        return appResult;
    }

    /**
     * 执法视频
     *
     * @param queryCondition
     * @return
     */
    @MyPower(name = "获取执法视频新", url = "/selectLawEnforcementVideo", isPublic = true)
    @RequestMapping("/selectLawEnforcementVideo")
    public AppResult selectLawEnforcementVideo(@RequestBody JSONObject queryCondition) {
        AppResult appResult = new AppResult();
        JSONObject data = new JSONObject();
        log.info("user query...");
        Video video1 = new Video();
        int pageNum = queryCondition.getIntValue("pageNum");
        int pageSize = queryCondition.getIntValue("pageSize");
        video1.setQueryCondition(queryCondition);
        video1.setPage(pageNum, pageSize);
        if (StringUtil.isEmpty(video1.getUnitCodes())) {
            data.put("value", 0);
            appResult.setCode(-1);
            appResult.setMsg("参数为空");
            appResult.setData(data);

            return appResult;
        }
        String[] unitCodes = video1.getUnitCodes().split(",");
        video1.setArray(unitCodes);
        List<Video> orderList = videoService.selectLawEnforcementVideo(video1);
        PageInfo<Video> dataGrid = new PageInfo<>(orderList);
        data.put("datagrid", dataGrid);
        appResult.setCode(200);
        appResult.setMsg("query success");
        appResult.setData(data);
        return appResult;

    }

    /**
     * 公共视频
     *
     * @param queryCondition
     * @return
     */
    @MyPower(name = "获取公共视频信息", url = "/selectPublicVideo", isPublic = true)
    @RequestMapping("/selectPublicVideo")
    public AppResult selectPublicVideo(@RequestBody JSONObject queryCondition) {
        AppResult appResult = new AppResult();
        JSONObject data = new JSONObject();
        log.info("user query...");
        Video video1 = new Video();
        int pageNum = queryCondition.getIntValue("pageNum");
        int pageSize = queryCondition.getIntValue("pageSize");
        video1.setQueryCondition(queryCondition);
        video1.setPage(pageNum, pageSize);
        if (StringUtil.isEmpty(video1.getUnitCodes())) {
            data.put("value", 0);
            appResult.setCode(-1);
            appResult.setMsg("参数为空");
            appResult.setData(data);
            return appResult;
        }
        String[] unitCodes = video1.getUnitCodes().split(",");
        video1.setArray(unitCodes);
        List<Video> orderList = videoService.selectPublicVideo(video1);
        PageInfo<Video> dataGrid = new PageInfo<>(orderList);
        data.put("datagrid", dataGrid);
        appResult.setCode(200);
        appResult.setMsg("query success");
        appResult.setData(data);
        return appResult;

    }

    /**
     * 通过案件编号查询案件详情信息
     *
     * @param caseCode
     * @return
     */
    @MyPower(name = "通过案件编号查询案件详情信息", url = "/selectCaseByCode", isPublic = true)
    @RequestMapping("/selectCaseByCode")
    public AppResult selectCaseByCode(String caseCode) {
        log.info("caseCode:{}", JSONObject.toJSONString(caseCode));
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        List<Video> list = videoService.selectCaseByCode(caseCode);
        data.put("list", list);
        result.setCode(200);
        result.setMsg("查询案件信息成功!");
        result.setData(data);
        return result;
    }

    /**
     * 删除视频
     *
     * @param
     * @return
     */
    @MyPower(name = "删除视频信息", url = "/deleteVideoById", isPublic = true)
    @RequestMapping("/deleteVideoById")
    public AppResult deleteVideoById(@RequestBody JSONObject jsonObject) {
        log.info("jsonObject:{}", JSONObject.toJSONString(jsonObject));
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        JSONArray array = jsonObject.getJSONArray("listArray");//前台传的集合
        JSONObject json = null;
        int j = 0;
        int M = 0;
        if (array != null && array.size() > 0) {
            for (int i = 0; i < array.size(); i++) {
                json = (JSONObject) array.get(i);
                String id = json.get("ides").toString();
                String videoSource = json.get("videoSource").toString();
                j = videoService.deleteVideoById(id, videoSource);
                M += j;
            }
        }
        if (M == array.size()) {
            data.put("j", j);
            result.setCode(200);
            result.setMsg("删除视频一个或多个成功!");
            result.setData(data);
        } else {
            data.put("value", 0);
            result.setCode(-1);
            result.setMsg("删除一个或多个视频失败!");
            result.setData(data);
        }
        return result;
    }

    /**
     * 视频关联
     *
     * @param
     * @return
     */
    @MyPower(name = "将视频关联信息", url = "/updateVideoRelationById", isPublic = true)
    @RequestMapping("/updateVideoRelationById")
    public AppResult updateVideoRelationById(@RequestBody JSONObject jsonObject) {
        log.info("jsonObject:{}", JSONObject.toJSONString(jsonObject));
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        JSONArray array = jsonObject.getJSONArray("listArray");//前台传的集合
        String correlationSuspectId = jsonObject.getString("correlationSuspectId");
        String correlationCaseCode = jsonObject.getString("correlationCaseCode");
        String correlationPoliceId = jsonObject.getString("correlationPoliceId");
        String materialTypeId = jsonObject.getString("materialTypeId");
        String documentName = jsonObject.getString("documentName");
        JSONObject json = null;
        int J = 0;
        int M = 0;
        if (array != null && array.size() > 0) {
            for (int i = 0; i < array.size(); i++) {
                json = (JSONObject) array.get(i);
                String id = json.get("id").toString();
                String videoSource = json.get("videoSource").toString();
                Video video = new Video();
                video.setId(id);
                video.setVideoSource(videoSource);
                video.setCorrelationSuspectId(correlationSuspectId);
                video.setCorrelationCaseCode(correlationCaseCode);
                video.setCorrelationPoliceId(correlationPoliceId);
                video.setMaterialTypeId(materialTypeId);
                video.setDocumentName(documentName);
                M = videoService.updateVideoRelationById(video);
                J += M;
            }
        }

        if (J == array.size()) {
            data.put("M", M);
            result.setCode(200);
            result.setMsg("视频关联成功!");
            result.setData(data);
        } else {
            data.put("value", 0);
            result.setCode(-1);
            result.setMsg("视频关失败!");
            result.setData(data);
        }
        return result;
    }

    /**
     * 视频编辑
     *
     * @param
     * @return
     */
    @MyPower(name = "编辑视频信息", url = "/editVideoById", isPublic = true)
    @RequestMapping("/editVideoById")
    public AppResult editVideoById(@RequestBody Video video) {
        log.info("video:{}", JSONObject.toJSONString(video));
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        if (StringUtil.isEmpty(video.getVideoSource())) {
            result.setCode(-1);
            result.setMsg("类型不能为空!");
            result.setData(data);
            return result;
        }

        int i = videoService.editVideoById(video);
        if (i > 0) {
            data.put("i", i);
            result.setCode(200);
            result.setMsg("视频编辑成功!");
            result.setData(data);
        } else {
            data.put("value", 0);
            result.setCode(-1);
            result.setMsg("视频编辑失败!");
            result.setData(data);
        }
        return result;
    }

    /**
     * 根据id查询视频详情信息
     *
     * @param id
     * @return
     */
    @MyPower(name = "查询视频详情信息", url = "/selectVideoById", isPublic = true)
    @RequestMapping("/selectVideoById")
    public AppResult selectVideoById(String id, String videoSource) {
        log.info("id:{}", JSONObject.toJSONString(id));
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        if (StringUtil.isEmpty(id) || StringUtil.isEmpty(videoSource)) {
            data.put("list", -1);
            result.setCode(-1);
            result.setMsg("传值为空！");
            result.setData(data);
            return result;
        }
        Map map = videoService.selectVideoById(id, videoSource);
        if (map.size() != 0) {
            data.put("list", map);
            result.setCode(200);
            result.setMsg("查询视频信息成功!");
            result.setData(data);
        } else {
            data.put("value", 0);
            result.setCode(200);
            result.setMsg("查询视频信息失败或为空!");
            result.setData(data);
        }
        return result;
    }

    /**
     * 视频上传
     *
     * @param vo
     * @return
     */
    @MyPower(name = "视频上传", url = "/uploadVideo", isPublic = true)
    @RequestMapping("/uploadVideo")
    public AppResult uploadVideo(PubliceVideo vo, MultipartFile file) throws IOException {
        AppResult appResult = new AppResult();
        JSONObject date = new JSONObject();
        //MultipartFile file = vo.getFile();
        if (file != null) {

            //存储文件夹地址
            String folderPath = ConstantUtil.VIDEOMANAGE_PATH;
            //获取当前时间毫秒数
            String trueFileName = String.valueOf(System.currentTimeMillis());
            // 文件原名称
            String fileName = file.getOriginalFilename();
            // 获取文件类型
            String fileType = fileName.substring(fileName.lastIndexOf("."));
            // 设置存放图片文件的路径
            String path = folderPath + trueFileName + fileType;//磁盘存储路径

            byte[] b =file.getBytes();
           boolean bl = false;
            //判断是否使用XSKY存储
//            if (ConstantUtil.XSKYRESTORAGE) {
                if (bl) {
                ObjectMetadata meta = new ObjectMetadata();
                meta.setContentType(file.getContentType());
                xskyService.uploadObjectForInputStream(ConstantUtil.XSKY_BUCKET_DOSSIER, path, b, meta);

                vo.setVideoPath(ConstantUtil.XSKY_PREPATH_URL + path);
                vo.setPlayPosition(path);
                vo.setId(StringUtil.generatorUUID());

                //设置图片路径
                int value = videoService.uploadVideo(vo,file);
                if (value > 0) {
                    date.put("value", 1);
                    appResult.setCode(200);
                    appResult.setMsg("视频上传成功!");
                    appResult.setData(date);
                } else {
                    date.put("value", 1);
                    appResult.setCode(200);
                    appResult.setMsg("视频上传失败!");
                    appResult.setData(date);

                }

            }else{

                vo.setVideoPath(ConstantUtil.PDF_PATH + path);
                vo.setPlayPosition(path);
                vo.setId(StringUtil.generatorUUID());
                //生成文件夹
                File folderFile = new File(folderPath);
                if (!folderFile.exists()) {
                    folderFile.mkdirs();
                }
                // 转存文件到指定的路径
                try {
                    FileOutputStream out = null;
                    out = new FileOutputStream(path);
                    out.write(b);
                    out.flush();
                    out.close();
                } catch (Exception e) {
                    log.info("视频上传失败");
                }
                //设置图片路径
                int value = videoService.uploadVideo(vo,file);
                if (value > 0) {
                    date.put("value", 1);
                    appResult.setCode(200);
                    appResult.setMsg("视频上传成功!");
                    appResult.setData(date);
                } else {
                    date.put("value", 1);
                    appResult.setCode(200);
                    appResult.setMsg("视频上传失败!");
                    appResult.setData(date);

                }
            }
        }
        return appResult;
    }

    /**
     * 根据单位编号查询民警下拉框
     *
     * @param
     * @return
     */
    @MyPower(name = "根据单位编号查询民警", url = "/selectPoliceByUnitcodes", isPublic = true)
    @RequestMapping("/selectPoliceByUnitcodes")
    public AppResult selectPoliceByUnitcodes(String unitCodes,String policeCode) {
        log.info("unitCodes:{}", JSONObject.toJSONString(unitCodes));
        AppResult appResult = new AppResult();
        JSONObject data = new JSONObject();
        if (StringUtil.isEmpty(unitCodes)) {
            data.put("value", 0);
            appResult.setCode(-1);
            appResult.setMsg("参数为空");
            appResult.setData(data);
            return appResult;
        }
        List<PoliceVo> list = videoService.selectPoliceByUnitcodes(unitCodes,policeCode);
        if (list.size() != 0) {
            data.put("list", list);
            appResult.setCode(200);
            appResult.setMsg("根据单位编号查询民警下拉框成功!");
            appResult.setData(data);
        }
        return appResult;
    }

    /**
     * 查询所有单位编号
     *
     * @return
     */
    @MyPower(name = "查询所有单位编号和名称", url = "/selectUnicodeAndName", isPublic = true)
    @RequestMapping("selectUnicodeAndName")
    public AppResult selectUnicode() {
        AppResult appResult = new AppResult();
        JSONObject date = new JSONObject();
        List<PoliceVo> list = videoService.selectUnicodeAndName();
        date.put("list", list);
        appResult.setCode(200);
        appResult.setMsg("查询所有单位编号成功");
        appResult.setData(date);
        return appResult;
    }

    /**
     * 查询音视频关联率百分比
     *
     * @return
     */
    @MyPower(name = "查询音视频关联率百分比", url = "/selectPercentage", isPublic = true)
    @RequestMapping("selectPercentage")
    public AppResult selectPercentage(String policeId) {
        AppResult appResult = new AppResult();
        JSONObject date = new JSONObject();
        String percentage = videoService.selectPercentage(policeId);
        date.put("percentage", percentage);
        appResult.setCode(200);
        appResult.setMsg("查询音视频关联率百分比成功");
        appResult.setData(date);
        return appResult;
    }

    /**
     * 执法音视频关联率情况列表
     *
     * @param queryCondition state=0 未关联,state=1,已关联
     * @return
     */
    @MyPower(name = "执法音视频关联率情况列表", url = "/aVCorrelation", isPublic = true)
    @RequestMapping("aVCorrelation")
    public AppResult AVCorrelation(@RequestBody JSONObject queryCondition) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        log.info("queryCondition:{}", JSONObject.toJSONString(queryCondition));
        log.info("user query...");
        int pageNum = queryCondition.getIntValue("pageNum");
        int pageSize = queryCondition.getIntValue("pageSize");
        TSuspec vo = new TSuspec();
        vo.setPage(pageNum, pageSize);
        vo.setQueryCondition(queryCondition);
        List<TSuspec> orderList = videoService.aVCorrelation(vo);
        // 用PageInfo对结果进行包装
        PageInfo<TSuspec> pageInfo = new PageInfo<>(orderList);
        DataGrid dataGrid = new DataGrid(pageInfo.getTotal(), pageInfo.getList());
        data.put("datagrid", dataGrid);
        result.setCode(200);
        result.setMsg("查询执法音视频关联率情况列表成功！");
        result.setData(data);
        return result;
    }

    /**
     * 根据案件编号查询所有卷宗关联情况(执法音视频关联二级页面)
     *
     * @param queryCondition
     * @return
     */
    @MyPower(name = "根据案件编号查询所偶有卷宗关联情况(执法音视频关联二级页面)", url = "/selectAuditDetailsByCasecode", isPublic = true)
    @RequestMapping("selectAuditDetailsByCasecode")
    public AppResult selectAuditDetailsByCasecode(@RequestBody JSONObject queryCondition) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        log.info("queryCondition:{}", JSONObject.toJSONString(queryCondition));
        log.info("user query...");
        int pageNum = queryCondition.getIntValue("pageNum");
        int pageSize = queryCondition.getIntValue("pageSize");
        AuditResult vo = new AuditResult();
        vo.setPage(pageNum, pageSize);
        vo.setQueryCondition(queryCondition);
        List<AuditResult> orderList = videoService.selectAuditDetailsByCasecode(vo);
        // 用PageInfo对结果进行包装
        PageInfo<AuditResult> pageInfo = new PageInfo<>(orderList);
        DataGrid dataGrid = new DataGrid(pageInfo.getTotal(), pageInfo.getList());
        data.put("datagrid", dataGrid);
        result.setCode(200);
        result.setMsg("根据案件编号查询所偶有卷宗关联情况！");
        result.setData(data);
        return result;
    }

}